package org.example.mynote.service.Impl;

import org.example.mynote.Entity.Notebook;
import org.example.mynote.Entity.User;
import org.example.mynote.mapper.NotebookMapper;
import org.example.mynote.mapper.UserMapper;
import org.example.mynote.service.NotebookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.NOT_FOUND;

@Service
public class NotebookServiceImpl implements NotebookService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NotebookMapper notebookMapper;

    @Override
    public List<Notebook> getNotebooksForCurrentUser() {
        User currentUser = getCurrentUser();
        // 3. 使用 userId 查询笔记本
        return notebookMapper.findByUserId(currentUser.getId());
    }

    @Override
    public Notebook createNotebook(String name) {
        User currentUser = getCurrentUser();
        Notebook notebook = new Notebook();
        notebook.setName(name);
        notebook.setUserId(currentUser.getId());
        notebookMapper.insert(notebook);
        return notebook;
    }

    @Override
    public Notebook updateNotebook(Long id, String name) {
        User currentUser = getCurrentUser();
        // 检查笔记本是否存在
        Notebook notebook = (Notebook) notebookMapper.findById(id)
                .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "未找到对应笔记本，ID为" + id));
        //检查笔记本是否属于当前用户
        if (!notebook.getUserId().equals(currentUser.getId())) {
            throw new ResponseStatusException(FORBIDDEN, "无响应笔记本项目");
        }
        //  更新并保存
        notebook.setName(name);
        notebookMapper.update(notebook);
        return notebook;
    }

    @Override
    public void deleteNotebook(Long id) {
        User currentUser = getCurrentUser();
        // 检查笔记本是否存在
        Notebook notebook = (Notebook) notebookMapper.findById(id)
                .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "未找到对应笔记本，ID为" + id));
        //检查笔记本是否属于当前用户
        if (!notebook.getUserId().equals(currentUser.getId())) {
            throw new ResponseStatusException(FORBIDDEN, "无响应笔记本项目");
        }

        // 3. 执行删除
        notebookMapper.deleteById(id);
    }

    // 辅助方法：获取当前登录的用户实体
    private User getCurrentUser() throws UsernameNotFoundException {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return userMapper.findByUsername(username);
    }
}
